package com.estasenposse.tdam.parsers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
//import java.util.jar.Attributes;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.estasenposse.tdam.entities.Noticia;

public class RssHandler extends DefaultHandler {
	private List<Noticia> noticias;
	private Noticia noticiaActual;
	private StringBuilder sbTexto;

	public List<Noticia> getNoticias() {
		return noticias;
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {

		super.characters(ch, start, length);

		if (this.noticiaActual != null) {
			// builder.append(ch, start, length);
			sbTexto.append(ch, start, length);
		}
	}

	@Override
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		
		super.endElement(uri, localName, name);
		//SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); 
		SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		if (this.noticiaActual != null) {
			
			if (localName.equals("title")) {
				noticiaActual.setTitle(sbTexto.toString());
			} else if (localName.equals("id")) {
				noticiaActual.setID(sbTexto.toString());
			} else if (localName.equals("tipo")) {
				noticiaActual.setTipo(sbTexto.toString());
			} else if (localName.equals("image")) {
				noticiaActual.setImage(sbTexto.toString());
			} else if (localName.equals("link")) {
				noticiaActual.setLink(sbTexto.toString());
			} else if (localName.equals("description")) {
				noticiaActual.setDescription(sbTexto.toString());
			} else if (localName.equals("subtitle")) {
				noticiaActual.setSubtitle(sbTexto.toString());
			} else if (localName.equals("pubDate")) {
				try {
					noticiaActual.setPubDate(format.parse(sbTexto.toString()));
				} catch (ParseException e) {
					System.out.println("No se pudo parsear la fecha!!");
					e.printStackTrace();
				}
			} else if (localName.equals("galeria")) {
				noticiaActual.setGaleria(sbTexto.toString());
			} else if (localName.equals("item")) {
				noticias.add(noticiaActual);
			}
			sbTexto.setLength(0);
		}
	}

	@Override
	public void startDocument() throws SAXException {

		super.startDocument();
		noticias = new ArrayList<Noticia>();
		sbTexto = new StringBuilder();
	}

	@Override
	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {

		super.startElement(uri, localName, name, attributes);

		if (localName.equals("item")) {
			noticiaActual = new Noticia();
		}
	}
}
